<template>
  <div>
    <div class="tableFiltersWrap">
      <el-row class="txt-right">
        <el-col>
          <v-form :fields="fields" :fieldsData="tableParams">
            <el-col :span="4" class="txt-left">
              <el-button type="primary" @click="fecthData">查询</el-button>
              <el-button type="default" @click="reloadData">清空</el-button>
            </el-col>
          </v-form>
        </el-col>
      </el-row>
    </div>
    <v-page>
      <el-card shadow="never" class="card-header-tabs">
        <div slot="header" class="clearfix">
          <div class="txt-right fn-pr15">
            <v-btn type="add" @handleClick="openSaveDialog"></v-btn>
            <v-btn type="del" @handleClick="del"></v-btn>
          </div>
        </div>
        <div class="text item">
          <basic-table ref="basicTable" :columns="columns" :call-server="callServer" @selectionChange="selectionChange" :height="height"
            v-model="tableParamsCopy"></basic-table>
        </div>
        <v-dialog ref="saveDialog" width="600px" @handleClose="saveItem"
          :title="isEmptyObject(currentItem) ? '新增预算' : '修改预算'">
          <save-form ref="saveItemForm" :patch-data="currentItem"></save-form>
        </v-dialog>      
      </el-card>
    </v-page>
  </div>
</template>

<script>
import { list, add, edit, remove } from '#/api/budgetManage';
import basicTable from "_c/tables";
import saveForm from "./saveForm";
import { queryDeptlist } from "#/api/public";
import { getCommonOptions } from '@/api/common'


export default {
  components: {
    basicTable,
    saveForm,
  },
  created() {
    getCommonOptions('YWLX').then(res => {
      this.typeList = res.data.map(d => ({ value: d.dmcode, label: d.dmname }))
    });
    queryDeptlist({ pageSize: 1000 }).then((res)=>{
      this.deptsListOptions = res.data.map(d => ({ label: d.deptName, value: d.deptId }));
    });  
    window.addEventListener('resize', this.handleResize);
  },
  destroyed() {
    window.removeEventListener('resize', this.handleResize);
  },
  data() {
    return {
      typeList: [],
      deptsListOptions: [],
      tableParams: {
        truename: "",
        username: "",
        deptid: "",
        usertype: "",
      },
      multipleSelection: [],
      form: {
        dels: '',
        ids: '',
        radio: '0',
        pwd: '',
      },
      currentItem: {},
      height: window.innerHeight - 320
    };
  },
  computed: {
    tableParamsCopy() {
      const params = {};
      if (this.tableParams.year) {
        params.year = this.tableParams.year.substring(0, 4);
      }
      return params;
    },
    fields() {
      return [
        {
          label: "",
          prop: "year",
          type: "date",
          dType: "year",
          span: 4,
          placeholder: "请选择年份",
        },
      ]
    },
    columns() {
      return [
        {
          label: "部门/中心",
          prop: "deptName",
        },
        {
          label: "预算类型",
          prop: "fundType",
          render: (h, row) => {
            return <span>{ (this.typeList.find(t => t.value == row.fundType) || {}).label }</span>
          }
        },
        {
          label: "预算金额",
          prop: "budgetAmount",
          render: (h, row) => {
            return <span>{ row.budgetAmount && row.budgetAmount.toFixed(2)}</span>
          }
        },
        {
          label: "可用预算/预算",
          prop: "budgetAmount",
          render: (h, row) => {
            return <span>{ row.availableBudget && row.availableBudget.toFixed(2)}/{ row.budgetAmount && row.budgetAmount.toFixed(2)}</span>
          }
        },
        {
          label: "自然年",
          prop: "year",
          width: 80
        },
        {
          label: "备注",
          prop: "remark",
        },
        {
          label: "创建人",
          prop: "createXm"
        },
        {
          label: "创建时间",
          prop: "createTime"
        },
        {
          label: "操作",
          fixed: "right",
          width: 120,
          render: (h, row) => {
            return (
              <div>
                <el-button
                  type="text"
                  onClick={() => this.openSaveDialog(row)}
                  size="middle"
                  class="txt-highlight"
                >
                  修改
                </el-button>
                <el-button
                  type="text"
                  onClick={() => this.del(row)}
                  size="middle"
                  class="txt-highlight"
                >
                  删除
                </el-button>
              </div>
            );
          },
        },
      ]
    }
  },
  methods: {
    handleResize() {
      this.height = window.innerHeight - 320;
    },
    callServer() {
      return list;
    },
    fecthData() {
      this.$refs.basicTable.fecthData();
    },
    reloadData() {
      this.tableParams = {}
      this.$refs.basicTable.reload();
    },
    selectionChange(val) {
      this.multipleSelection = val;
    },
    handleNodeClick(node) {
      if (node.children) {
        this.currentNode = node;
        this.fecthData(node.id);
      }
    },
    openSaveDialog(item) {
      this.currentItem = Object.assign({}, item || {});
      if (this.currentItem.year) {
        this.currentItem.year = this.currentItem.year + '-01-01';
      }
      this.$refs.saveDialog.dialogVisible = true;
    },
    saveItem() {
      const me = this;
      this.$refs.saveItemForm.validate((data) => {
        const params = Object.assign({}, data)
        this.$refs.saveDialog.posting = true;
        params.year = params.year ? params.year.substring(0, 4) : '';
        if (this.$refs.saveItemForm.status) {
          edit(params)
            .then(() => {
              this.$refs.saveDialog.close();
              me.toast("修改成功", "success");
              me.fecthData();
            }).catch((err) => {
              this.$refs.saveDialog.posting = false;
            });
        } else {
          add(params)
            .then(() => {
              this.$refs.saveDialog.close();
              me.toast("添加成功", "success");
              me.fecthData();
            })
            .catch((err) => {
              this.$refs.saveDialog.posting = false;
            });
        }
      });
    },
    del(item) {
      let me = this;
      let dels = [];
      let ids = [];
      if (item) {
        dels.push(item.year + item.fundType);
        ids.push(item.id);
      } else {
        if (!this.multipleSelection.length) {
          this.toast("请选择至少一条数据", "warning");
          return
        }
        for (let ml of this.multipleSelection) {
          dels.push(ml.year + ml.fundType);
          ids.push(ml.id);
        }
      }
      this.alert("删除预算：" + dels.join(",") + "。", "确认要进行删除吗？", {
        type: "warning",
        request() {
          return remove({ids: ids.join(",")});
        },
        success() {
          me.toast("删除成功", "success");
          me.fecthData();
        },
      });
    },    
  },
};
</script>